package com.graph;

/**
 * @Author: tgy
 * @Date: 2020-10-23 10:07
 */
@SuppressWarnings("unchecked")
public class GraphFactory {

    public static Graph<Object,Double> generateDirectGraph(Class<? extends Graph> clazz, Object[][] datas) {

        Graph<Object,Double> graph = null;

        try {

            graph = clazz.newInstance();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return generateDirectGraph(graph,datas);
    }

    public static <V> Graph<V, Double> generateDirectGraph(Graph<V,Double> graph, Object[][] datas) {

        for (Object[] data : datas) {

            if (data.length == 0) {

                graph.addVertex((V)data[0]);
            }else if (data.length == 2) {

                graph.addEdge((V)data[0],(V)data[1]);
            }else if (data.length == 3) {

                graph.addEdge((V)data[0],(V)data[1],Double.parseDouble(data[2].toString()));
            }
        }

        return graph;

    }

    public static  Graph<Object,Double> generateUnDirectGraph(Class<? extends Graph> clazz, Object[][] datas) {

        Graph<Object,Double> graph = null;

        try {

            graph = clazz.newInstance();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return generateUnDirectGraph(graph,datas);
    }

    public static <V>  Graph<V,Double> generateUnDirectGraph(Graph<V,Double> graph, Object[][] datas) {

        for (Object[] data : datas) {

            if (data.length == 0) {

                graph.addVertex((V)data[0]);
            }else if (data.length == 2) {

                graph.addEdge((V)data[0],(V)data[1]);
                graph.addEdge((V)data[1],(V)data[0]);
            }else if (data.length == 3) {

                graph.addEdge((V)data[0],(V)data[1],Double.parseDouble(data[2].toString()));
                graph.addEdge((V)data[1],(V)data[0],Double.parseDouble(data[2].toString()));
            }
        }

        return graph;
    }
}
